//
//  DetialViewController.m
//  HumorousSript
//
//  Created by 李欢 on 15/6/22.
//  Copyright (c) 2015年 李欢. All rights reserved.
//

#import "DetialViewController.h"
#import <UIImageView+WebCache.h>
#import "SANetWorkingTask.h"
#import "DetailTableViewCell.h"
#import "MJRefresh.h"
#import "CartoonButton.h"
#import "HistoryDatabase.h"
#import "HistoryModel.h"
#define Width [UIScreen mainScreen].bounds.size.width
#define Height [UIScreen mainScreen].bounds.size.height


@interface DetialViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, retain) UITableView * tableView;
@property (nonatomic, retain) NSMutableArray * tableArray;
@property (nonatomic, assign) int i;
@property (nonatomic, strong) CartoonButton *button;
@end

@implementation DetialViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    self.tableArray = [NSMutableArray array];
        self.i = 20;
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor ]];
//    http://isub.snssdk.com/2/data/v2/get_essay_comments/?iid=2808558815&sort=hot&tag=joke&offset=0&count=20&device_id=4272329077&%@&ac=WIFI&channel=tongbu&app_name=joke_essay&aid=7&version_code=4.1.0&device_platform=iphone&os_version=8.3
   
        NSString *str1 = @"&ac=WIFI&channel=tongbu&app_name=joke_essay&aid=7&version_code=4.1.0&device_platform=iphone&os_version=8.3&device_type=iPhone%205S&vid=B06E994A-E093-479F-99E0-351D9340559F&openudid=e00e3962e37339ec7ce09708cad23b19b7a0693b&os_api=18&idfa=E2FD8DB1-FBA8-40EA-8C02-FAB446839AD1&screen_width=640";
        NSString * url = [NSString stringWithFormat:@"http://isub.snssdk.com/2/data/v2/get_essay_comments/?iid=2808558815&sort=hot&tag=joke&offset=0&count=20&device_id=4272329077&group_id=%@%@",self.groupId, str1];
    
    
    [SANetWorkingTask request:url parmater:nil block:^(NSDictionary *result) {
        NSDictionary * dic = [result objectForKey:@"data"];
        NSMutableArray * array = [dic objectForKey:@"recent_comments"];
        
        
        
        self.tableArray = [NSMutableArray arrayWithArray:array];
        
        [self creatView];

        [self.tableView reloadData];
    }];
    //收藏按钮
    self.button = [[CartoonButton alloc] initWithFrame:CGRectMake(0, 0, 40/375.0*Width, 40/667.0*Height)];
    [_button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithCustomView:_button];
    self.navigationItem.rightBarButtonItem = button1;
    
    NSMutableArray *array = (NSMutableArray *)[HistoryDatabase selectID:self.groupId];
    //设置收藏按钮图片
    if ([array count] == 0) {
        
        [self.button setImage:[UIImage imageNamed:@"soucang.jpg"] forState:UIControlStateNormal];
    }else{
        
        [self.button setImage:[UIImage imageNamed:@"soucanghou.jpg"] forState:UIControlStateNormal];
    }

}

#pragma mark -
#pragma mark 收藏点击事件

- (void)buttonAction:(id)sender
{
    
    
#pragma mark-
#pragma mark 判断是否已收藏
    NSMutableArray *array = (NSMutableArray *)[HistoryDatabase selectID:self.groupId ];
    if ([array count] == 0 && [self.button.imageView.image isEqual:[UIImage imageNamed:@"soucang.jpg"]]) {
        
            [self.button setImage:[UIImage imageNamed:@"soucanghou.jpg"] forState:UIControlStateNormal];
        
            NSMutableArray *idArray = (NSMutableArray *)[HistoryDatabase selectID:self.groupId];
            
            //取得所有为空
            if (idArray.count == 0) {
                NSLog(@"所有数组为空");
                //判断登录状态
                
                    NSString * AnimationName = self.name;
                    NSString * AnimationPic = self.pic;
                    
                NSString *str = self.share;
                    HistoryModel * model = [HistoryModel HistoryModelWithHistoryId:self.groupId HistoryName:AnimationName HistoryPic:AnimationPic text:str];
                    
                    [HistoryDatabase insertWithModel:model];
                    
                
                
                
#pragma mark -
#pragma mark这里得判断人和id()
            }else{
                
                
                NSMutableArray *myPersonArray = (NSMutableArray *)[HistoryDatabase selectID:self.groupId ];
                //数组
                if (myPersonArray.count == 0) {
                    
                        NSString * AnimationName = self.name;
                        NSString * AnimationPic = self.pic;
                        
                        NSString *str = self.share;
                        HistoryModel * model = [HistoryModel HistoryModelWithHistoryId:self.groupId HistoryName:AnimationName HistoryPic:AnimationPic text:str];
                        
                        [HistoryDatabase insertWithModel:model];
                        
#pragma mark-
#pragma mark在这里是没有登陆
                    
                    
                }
            }
            
        }
        
     else if([self.button.imageView.image isEqual:[UIImage imageNamed:@"soucanghou.jpg"]]){
        //        [self.button setTitle:@"收藏" forState:UIControlStateNormal];
        [self.button setImage:[UIImage imageNamed:@"soucang.jpg"] forState:UIControlStateNormal];
        HistoryModel *myid = [[HistoryModel alloc]init];
        for (HistoryModel *model in array) {
            myid = model;
            NSLog(@"%@", model);
        }
        [HistoryDatabase deleteWithModel:myid];
        
    }
    
}

//创建tableView
-(void)creatView
{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width , self.view.frame.size.height) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorStyle = UITableViewCellStyleDefault;

    
    //设定上啦加载 下拉刷新
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect = [self.share boundingRectWithSize:CGSizeMake(335, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    UIView * header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, rect.size.height + 50/375.0*Width + 50/667.0*Height)];
    [header setBackgroundColor:[UIColor orangeColor]];
    
    
    
    
    UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(10/375.0*Width, 10/667.0*Height, 40/375.0*Width, 40/667.0*Height)];
    //        图片变成圆角
    imageview.layer.cornerRadius = 20;
    imageview.clipsToBounds = YES;
    [imageview sd_setImageWithURL:[NSURL URLWithString:self.pic] placeholderImage:nil options:SDWebImageRetryFailed];
    //        名字
    UILabel *alabel = [[UILabel alloc]initWithFrame:CGRectMake(60/375.0*Width, 10/667.0*Height, 300/375.0*Width, 30/667.0*Height)];
    alabel.text = self.name;
    
    //        内容
    UILabel  *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 60/375.0*Width, [UIScreen mainScreen].bounds.size.width, rect.size.height)];
    label.text = self.share;
    label.numberOfLines = 0;
    [header addSubview:imageview];
    [header addSubview:alabel];
    [header addSubview:label];
    
    
    //last
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 60/667.0*Height + rect.size.height, [UIScreen mainScreen].bounds.size.width, 30/667.0*Height)];
    
    
    self.LastView = [[CellView alloc] initWithFrame:CGRectMake(0, 0, view1.frame.size.width / 4.0, 30/667.0*Height)];
    self.LastView.image.image = [UIImage imageNamed:@"5.png"];
    self.LastView.lable1.text = self.lable1;
    //        self.LastView.backgroundColor = [UIColor greenColor];
    [view1 addSubview:self.LastView];
    
    
    self.LastView1 = [[CellView alloc] initWithFrame:CGRectMake(view1.frame.size.width / 4.0, 0,view1.frame.size.width / 4.0, 30/667.0*Height)];
    //        self.LastView1.backgroundColor = [UIColor orangeColor];
    self.LastView1.image.image = [UIImage imageNamed:@"6.png"];
    self.LastView1.lable1.text = self.lable2;

    
    [view1 addSubview:self.LastView1];
    
    self.LastView2 = [[CellView alloc] initWithFrame:CGRectMake(view1.frame.size.width / 4.0 * 2, 0, view1.frame.size.width / 4.0, 30/667.0*Height)];
    //        self.LastView2.backgroundColor = [UIColor blackColor];
    self.LastView2.image.image = [UIImage imageNamed:@"3.png"];
    self.LastView2.lable1.text = self.lable3;

    [view1 addSubview:self.LastView2];
    [header addSubview:view1];
    self.tableView.tableHeaderView = header;
    [self.view addSubview:self.tableView];
    
}
//上啦加载点击事件
- (void)loadMoreData
{
    NSString *str1 = @"&ac=WIFI&channel=tongbu&app_name=joke_essay&aid=7&version_code=4.1.0&device_platform=iphone&os_version=8.3&device_type=iPhone%205S&vid=B06E994A-E093-479F-99E0-351D9340559F&openudid=e00e3962e37339ec7ce09708cad23b19b7a0693b&os_api=18&idfa=E2FD8DB1-FBA8-40EA-8C02-FAB446839AD1&screen_width=640";
    NSString * url = [NSString stringWithFormat:@"http://isub.snssdk.com/2/data/v2/get_essay_comments/?iid=2808558815&sort=hot&tag=joke&offset=%d&count=20&device_id=4272329077&group_id=%@%@",self.i,self.groupId, str1];
    
    
    [SANetWorkingTask request:url parmater:nil block:^(NSDictionary *result) {
        NSDictionary * dic = [result objectForKey:@"data"];
        NSArray *array = [dic objectForKey:@"recent_comments"];
        if (array.count == 0) {
            [self.tableView removeFooter];
            return ;
        }

        for (NSDictionary *dic in array) {
            [self.tableArray addObject:dic];
        }
        
        
        NSLog(@"%@",[dic objectForKey:@"recent_comments"]);
//        [self.tableArray addObject:dic];
        
        
        
        
//        [self creatView];
        
        [self.tableView reloadData];
    }];
    // 拿到当前的上拉刷新控件，结束刷新状态
    
    self.i += 20;
    [self.tableView.footer endRefreshing];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * cellIdentify = @"cell";
    DetailTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[DetailTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    NSMutableDictionary * sDic = [self.tableArray objectAtIndex:indexPath.row];
    [cell.imageview sd_setImageWithURL:[sDic objectForKey:@"user_profile_image_url"] placeholderImage:nil];
    cell.name.text = [sDic objectForKey:@"user_name"];
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect = [[sDic objectForKey:@"text"] boundingRectWithSize:CGSizeMake(335, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];

    [cell.text setFrame:CGRectMake(10/375.0*Width, 80/667.0*Height, self.view.frame.size.width - 20/375.0*Width, rect.size.height)];
    cell.text.text = [sDic objectForKey:@"text"];
    
//    cell.count = [sDic objectForKey:@"digg_count"];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary * sDic = [self.tableArray objectAtIndex:indexPath.row];

    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect = [[sDic objectForKey:@"text"] boundingRectWithSize:CGSizeMake(335, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return 80/667.0*Height + rect.size.height + 10/667.0*Height;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
